<script lang='ts' setup>
import { useGetGroupMembers, exitGroup, deleteGroup } from '@/stores/group'
import { onMounted } from 'vue'
import { userId } from '@/stores/user'
import { splicingUrl } from '@/stores/loading'
import { ref } from 'vue'
import { format } from 'date-fns'
import { ElDrawer, ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'
import { middlePage, rightPage, friendAndGroupInfoDrawer } from '@/stores/page'
import { useChatRecordingStore } from '@/stores/chatRecording'
import { setFriendInfo } from '../../stores/friend';
import { useGetFriendStore } from '@/stores/getFriend';
import type { UploadInstance } from 'element-plus'

const getFriendStore = useGetFriendStore()
const chatRecordingStore = useChatRecordingStore()
const getGroupMembers = useGetGroupMembers()
const props = defineProps({
    groupId: Number,
    groupName: String,
    groupMasterId: Number,
})

const loading = ref(false)

let timer

const cancelForm = () => {
    loading.value = true
    setTimeout(() => {
        loading.value = false
        dialog.value = false
    }, 400)
}

const handleClose = (done : any) => {
    if (loading.value) {
        return
    }
    ElMessageBox.confirm('是否退出申请', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            loading.value = true
            timer = setTimeout(() => {
                done()
                // 动画关闭需要一定的时间
                setTimeout(() => {
                    loading.value = false
                }, 400)
            }, 2000)
        })
        .catch((error) => {
            console.log(error)
        })
}

// 获取群成员
onMounted(() => {
    getGroupMembers.get(props.groupId, userId.value)
})

const user = ref()
const dialogVisible = ref(false)
function show(item : any) {
    dialogVisible.value = true
    user.value = item
}

const dialog = ref(false)
const input = ref('')

function send(item) {
    //关闭弹窗和抽屉
    dialogVisible.value = false
    friendAndGroupInfoDrawer.value = false
    middlePage.value = 1
    //将聊天好友的信息储存到会话储存中
    sessionStorage.setItem('friend', JSON.stringify(item));
    //更改会话的好友信息
    setFriendInfo()
    //获取聊天记录
    chatRecordingStore.getChatRecordingList();
    rightPage.value = 1
}

function apply(){
    dialog.value = true
}

const onClick = () => {
    loading.value = false
    dialog.value = false
    clearTimeout(timer)
    dialogVisible.value = false
    //发送好友申请
    axios({
        method : 'post',
        url : 'https://47.120.69.214:8787/friendApply/addApply',
        data:{
            "userId1" : userId.value,
            "userId2" : user.value.id,
            "content" : input.value
        },
        headers : {
            "Content-Type" : "application/json"
        }
    })
    .then(response => {
        ElMessage.success('发送成功')
    })
    .catch(error => {
        console.log(error)
    })
}

function exitG(){
    middlePage.value = 1;
    rightPage.value = 0;
    friendAndGroupInfoDrawer.value = false;
    exitGroup(userId.value,props.groupId)
    getFriendStore.getFriendList()
}

function deleteG(){
    middlePage.value = 1;
    rightPage.value = 0;
    friendAndGroupInfoDrawer.value = false;
    deleteGroup(props.groupId)
    getFriendStore.getFriendList()
}




const uploadRef = ref<UploadInstance>()
function handleSuccess(file: File, response: any) {
  const formData = new FormData()
  formData.append('head', response.raw)
  formData.append('groupId', props.groupId+'')
  axios.post('https://47.120.69.214:8787/group/uploadHead', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  .then(response => {
    getFriendStore.getFriendList()
  })
    .catch(error => console.log(error))
}

</script>

<template>
    <el-upload ref="uploadRef" class="upload-demo" action="https://47.120.69.214:8787/group/uploadHead"
        :data="{ 'groupId': groupId }"
        name="head"
          :on-success="handleSuccess" :show-file-list="false" list-type="picture" accept="images">
          <template #trigger>
            <el-button type="success" v-if="userId === groupMasterId+''" style="margin:10px">更换头像</el-button>
          </template>
        </el-upload>
    <el-card class="card" shadow="always">昵称: {{ groupName }}</el-card>
    <el-card class="card" shadow="always">ID: {{ groupId }}</el-card>
    <label style="font-size:20px">群成员</label>
    <el-scrollbar style="height:20vw;width:20vw; left:20%">
        <div v-for="item in getGroupMembers.groupMembers" :key="item" class="scrollbar-demo-item2" @click="show(item)">
            <el-image style="width: 3vw; height: 6vh;margin-left:5%" :src="splicingUrl(item.headShotUrl)"
                :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[splicingUrl(item.headShotUrl)]"
                fit="cover" />
            <label style="font-size:20px;margin-top:3.5%; margin-left:10%"> {{ item.name }} </label>
        </div>
    </el-scrollbar>
    <el-button type="danger" @click="exitG()" v-if="userId !== groupMasterId+''" class="button3">退出群聊</el-button>
    <el-button type="danger" @click="deleteG()" v-else class="button3">删除群聊</el-button>

    <el-dialog v-model="dialogVisible" title="个人信息" width="500">
    <div class="demo-image__preview">
      <el-image style="width: 100px; height: 100px; left:-30%; border:solid 1px" :src="splicingUrl(user.headShotUrl)" :zoom-rate="1.2"
        :max-scale="7" :min-scale="0.2" fit="cover" :preview-src-list="[splicingUrl(user.headShotUrl)]" />
    </div>
    <div style="margin-bottom:4%"></div>
    <el-scrollbar height="40vh">
      <div >
        <div class="scrollbar-demo-item">
          <div id="personalInfo">昵称: {{ user.name }}</div>
        </div>
        <div class="scrollbar-demo-item" v-if="user.isFriend">
          <div id="personalInfo">ID: {{ user.id }}</div>
        </div>
        <div class="scrollbar-demo-item">
          <div id="personalInfo">电话号码: {{ user.phone }}</div>
        </div>
        <div class="scrollbar-demo-item" v-if="user.isFriend">
          <div id="personalInfo" v-if="user.birthday !== null">生日: {{ format(user.birthday, 'yyyy-MM-dd') }}</div>
          <div id="personalInfo" v-else>生日: </div>
        </div>
        <div class="scrollbar-demo-item">
          <div id="personalInfo">性别: {{ user.gender }}</div>
        </div>
      </div>
    </el-scrollbar>

    <template #footer>
      <div class="dialog-footer">
        <div v-if="user.isFriend">
          <el-button type="success" @click="send(user)" class="button2">发送消息</el-button>
        </div>
        <div v-else>
          <el-button type="success" @click="apply()" class="button2">添加好友</el-button>
        </div>
      </div>
    </template>
  </el-dialog>

  <el-drawer v-model="dialog" title="好友申请" :before-close="handleClose" direction="ltr" class="demo-drawer">
        <el-input v-model="input" maxlength="50" style="width: 25vw;" placeholder="好友申请" show-word-limit :rows="5"
            type="textarea" />
        <div style="margin: 10% 0"></div>
        <el-button type="primary" @click="onClick()">发送申请</el-button>
        <el-button :loading="loading" @click="cancelForm" style="margin-left:15%;">
            {{ loading ? '退出申请 ...' : '退出申请' }}
        </el-button>
    </el-drawer>

</template>

<style scoped>
.card {
    display: flex;
    justify-content: left;
    align-items: left;
    margin-bottom: 10px;
    font-size: 20px;
}

.scrollbar-demo-item2 {
    display: flex;
    align-items: left;
    justify-content: left;
    height: 50px;
    margin: 10px;
    text-align: left;
    border-radius: 4px;
    background: var(--el-color-primary-light-9);
}

#personalInfo {
  font-size: 20px;
  margin-left: 10%
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: left;
  height: 50px;
  margin: 10px;
  text-align: left;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: balck;
  margin-left: 8%;
  width: 23vw
}

.button2 {
    font-size:20px;
    width:10vw;
    height:6vh;
    margin-right:40%
}

.button3 {
    font-size: 20px;
    width: 15vw;
    height: 8vh;
    margin-top:10%;
    margin-left:10%
}
</style>